import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import '../models/business_card.dart';

class DatabaseService {
  static final DatabaseService _instance = DatabaseService._internal();
  factory DatabaseService() => _instance;
  DatabaseService._internal();

  static Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    String path = join(await getDatabasesPath(), 'business_cards.db');
    return await openDatabase(
      path,
      version: 1,
      onCreate: _onCreate,
    );
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE business_cards(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        company TEXT NOT NULL,
        position TEXT NOT NULL,
        phone TEXT NOT NULL,
        email TEXT NOT NULL,
        address TEXT NOT NULL,
        website TEXT NOT NULL,
        image_path TEXT,
        notes TEXT,
        created_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
      )
    ''');
  }

  // 插入名片
  Future<int> insertBusinessCard(BusinessCard card) async {
    final db = await database;
    return await db.insert('business_cards', card.toMap());
  }

  // 获取所有名片
  Future<List<BusinessCard>> getAllBusinessCards() async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(
      'business_cards',
      orderBy: 'updated_at DESC',
    );
    return List.generate(maps.length, (i) => BusinessCard.fromMap(maps[i]));
  }

  // 根据ID获取名片
  Future<BusinessCard?> getBusinessCardById(int id) async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(
      'business_cards',
      where: 'id = ?',
      whereArgs: [id],
    );
    if (maps.isNotEmpty) {
      return BusinessCard.fromMap(maps.first);
    }
    return null;
  }

  // 更新名片
  Future<int> updateBusinessCard(BusinessCard card) async {
    final db = await database;
    return await db.update(
      'business_cards',
      card.toMap(),
      where: 'id = ?',
      whereArgs: [card.id],
    );
  }

  // 删除名片
  Future<int> deleteBusinessCard(int id) async {
    final db = await database;
    return await db.delete(
      'business_cards',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // 搜索名片
  Future<List<BusinessCard>> searchBusinessCards(String query) async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(
      'business_cards',
      where: '''
        name LIKE ? OR 
        company LIKE ? OR 
        position LIKE ? OR 
        phone LIKE ? OR 
        email LIKE ? OR 
        address LIKE ? OR 
        website LIKE ? OR 
        notes LIKE ?
      ''',
      whereArgs: List.filled(8, '%$query%'),
      orderBy: 'updated_at DESC',
    );
    return List.generate(maps.length, (i) => BusinessCard.fromMap(maps[i]));
  }

  // 获取名片总数
  Future<int> getBusinessCardCount() async {
    final db = await database;
    final result = await db.rawQuery('SELECT COUNT(*) as count FROM business_cards');
    return Sqflite.firstIntValue(result) ?? 0;
  }

  // 清空所有名片
  Future<void> clearAllBusinessCards() async {
    final db = await database;
    await db.delete('business_cards');
  }

  // 关闭数据库
  Future<void> close() async {
    final db = await database;
    await db.close();
  }
}
